/*
 * IMGLoader.cpp
 *
 *  Created on: 28.09.2013
 *      Author: dima
 */


#include "../Globals.hpp"

#include "../Model/GameObjectModel.hpp"

#include "IMGLoader.hpp"

#include <iostream>
#include <SDL/SDL_image.h>


Tanks::Resources::IMGLoader &
Tanks::
Resources::
IMGLoader::
getInstance()
{
  static IMGLoader instance;
  return instance;
}


Tanks::
Resources::
IMGLoader::
~IMGLoader()
{
  for(int iter = Tanks::Model::Player; iter < Tanks::Model::GameObjectTypeEnd; ++iter)
  {
    SDL_FreeSurface(m_images[iter]);
  }
}



void
Tanks::
Resources::
IMGLoader::
Load(std::string argDir)
{
  // WARNING: The order must NOT be changed!
  AddSurface(argDir + "Images" + Globals::directorySplitter + "Player.png", true);
  AddSurface(argDir + "Images" + Globals::directorySplitter + "Enemy_Easy.png", true);
  AddSurface(argDir + "Images" + Globals::directorySplitter + "Enemy_Medium.png", true);
  AddSurface(argDir + "Images" + Globals::directorySplitter + "Enemy_Hard.png", true);
  AddSurface(argDir + "Images" + Globals::directorySplitter + "Missile.png", true);
  AddSurface(argDir + "Images" + Globals::directorySplitter + "Explosion.png", true);
  AddSurface(argDir + "Images" + Globals::directorySplitter + "TankExplosion.png", true);
}


void
Tanks::
Resources::
IMGLoader::
AddSurface(std::string argImgFilename, bool argTransparent)
{
  SDL_Surface * surface = LoadImage(argImgFilename, argTransparent);
  if(surface == NULL) throw std::string(IMG_GetError());

  m_images.push_back(surface);
}



SDL_Surface *
Tanks::
Resources::
IMGLoader::
LoadImage(std::string argFilename, bool argTransparent)
{
  SDL_Surface * tempImg = NULL;

  tempImg = IMG_Load(argFilename.c_str());
  if(tempImg == NULL) return NULL;

  if(argTransparent)
  {
    Uint32 colorkey = SDL_MapRGB(tempImg->format, 0x00, 0x00, 0x00);
    SDL_SetColorKey(tempImg, SDL_SRCCOLORKEY, colorkey);
  }

  SDL_Surface * img = ConvertImage(tempImg);
  SDL_FreeSurface(tempImg);

  return img;
}


SDL_Surface *
Tanks::
Resources::
IMGLoader::
ConvertImage(SDL_Surface * argImg)
{
  SDL_Surface * img = NULL;
  img = SDL_DisplayFormat(argImg);

  if(img == NULL) return NULL;
  return img;
}


